package com.borun.controller.api;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.borun.entity.UserBean;
import com.borun.service.UserService;
import com.borun.util.RespUtils;
import com.borun.util.entity.RespStatus;

@Controller
@ResponseBody
@RequestMapping("api/")
public class AccountApiController {

	@Autowired
	private UserService userService;
	
	/**
	 * 登录
	 * 
	 * @param session
	 *            HttpSession
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public JSONObject toLogin(HttpSession session, UserBean userBean) { 

		UserBean loginuser = userService.login(userBean);
		System.out.println(userBean.getUsername() + ":" + userBean.getPassword());

		if (loginuser != null) {
			// 在Session里保存信息
			session.setAttribute("userToken", loginuser);
			return RespUtils.createSucResp("登录成功！");
		}
		// 账户不合法
		return RespUtils.createResp(RespStatus.FALSEAUTH, "用户名或密码错误");
	}
	
	
	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	public JSONObject toRegist(HttpSession session, UserBean userBean,String confrim) { 
		System.out.println("confrim:"+confrim+"username:"+userBean.getUsername()+"password:"+userBean.getPassword());
		try {
			if(!confrim.equals(userBean.getPassword()))
				return RespUtils.createResp(RespStatus.FALSEAUTH, "两次密码不一致");
			
			UserBean registuser = userService.regist(userBean);
			System.out.println(userBean.getUsername() + ":" + userBean.getPassword() + ":"+confrim);
			
			if (registuser != null) {
				// 在Session里保存信息
				session.setAttribute("userToken", registuser);
				return RespUtils.createSucResp("注册成功！");
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}

		// 账户不合法
		return RespUtils.createResp(RespStatus.FALSEAUTH, "账户已存在");
	}
	
	
	
	
	
	/**
	 * 退出系统
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/logout")
	public JSONObject logout(HttpSession session){
		// 清除Session
		session.invalidate();
		return RespUtils.createSucResp("注销成功！");
	}
	
}
